# 将剧本中的 任务和主机 抽象为类
import paramiko

class Host:
    def __init__(self, address, username, password):
        self.address = address
        self.username = username
        self.password = password

    def __repr__(self) -> str:
        return f"Host({self.address!r}, {self.username!r})"
    
    def execute_command(self, command):  # 抽像到Host类的原因，可以简单理解为这个命令是与host关联的
        print(f'Executing command:{command} on {host}')
            
        # 创建客户端对象
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            
            # 连接与执行
            client.connect(host, port, username, password)
            _, stdout, stderr = client.exec_command(command)
            # 获取执行结果状态码
            exit_status = stdout.channel.recv_exit_status()

            # 输出结果
            result = {
                "output": stdout.read().decode(),
                "error": stderr.read().decode(),
                "exit_status": exit_status
            }
            
        except Exception as e:
            result = {
                "stdout": "",
                "error": str(e),
                "exit_status": -1
            }
        
        finally:
            client.close()

        return result

    